package com.tool;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author Evan.Hu
 * 
 */
public class DBConfig {
	private DataCenterVO dcVO;

	public DBConfig(DataCenterVO dcVO) {
		if (dcVO == null)
			throw new IllegalArgumentException("ConnectionInfo construct arguments can't null");
		this.dcVO = dcVO;
	}

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public void testDB() throws Exception {

	}

	/**
	 * 获取JDBC连接
	 * 
	 * @return
	 * @throws Exception
	 */
	public Connection getJDBCConnection() throws Exception {
		java.sql.Driver drv = (java.sql.Driver) Class.forName(getDriverName()).newInstance();
		DriverManager.registerDriver(drv);
		Connection conn = DriverManager.getConnection(getJDBCUrl(), dcVO.getUserName(), dcVO.getPassword());
		return conn;
	}

	protected String getJDBCUrl() {
		StringBuilder url = new StringBuilder();
		switch (dcVO.getDbType()) {
		case 0:
			url.append("jdbc:microsoft:sqlserver://").append(dcVO.getDbAddr()).append(":").append(dcVO.getDbPort()).append(";DatabaseName=").append(dcVO.getDbName());
			break;
		case 1:
			url.append("jdbc:oracle:thin:@").append(dcVO.getDbAddr()).append(":").append(dcVO.getDbPort()).append(":").append(dcVO.getDbName());
			break;
		}

		return url.toString();
	}

	protected String getDriverName() {
		String key = "";
		String defaultDriver = "";
		if (dcVO.getDbType() == 0) {
			key = "SQLSERVER";
			defaultDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
		} else if (dcVO.getDbType() == 2) {
			key = "DB2";
			defaultDriver = "COM.ibm.db2.jdbc.app.DB2Driver";
		} else if (dcVO.getDbType() == 1) {
			key = "ORACLE";
			defaultDriver = "oracle.jdbc.driver.OracleDriver";
		}
		return defaultDriver;
	}

}
